package com.atguigu.product.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;

/**
 * @author Jia Fa
 * @create 2021-12-10 19:56
 */
@Configuration
@Slf4j
public class DeadConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;

    // 生产者消息确认机制一
    @PostConstruct
    public void init(){
        this.rabbitTemplate.setConfirmCallback((@Nullable CorrelationData correlationData, boolean ack, @Nullable String cause)->{
            if (!ack){
                log.error("消息到交换机失败,原因{},元信息{}", cause,correlationData);
            }
        });
        // 生产者确认机制二
        this.rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey)->{
            log.error("消息由交换机到队列失败,原因{},交换机{},路由键{},信息{}",
                    replyText,exchange,routingKey,new String(message.getBody()));
        });
    }

    // 死信队列
    @Bean("deadQueue")
    public Queue deadQueue(){
        return QueueBuilder.durable("DEAD_QUEUE").build();
    }
    // 死信交换机
    @Bean("deadEx")
    public Exchange deadExchange(){
        return ExchangeBuilder.topicExchange("TOPIC_DEAD_EX").durable(true).build();
    }

    // 绑定死信
    @Bean
    public Binding deadBinding(@Qualifier("deadQueue") Queue deadQueue,@Qualifier("deadEx") Exchange deadEx){
        return BindingBuilder.bind(deadQueue).to(deadEx).with("dead_fly.*").noargs();
    }

    @Bean
    public Queue deal(){
        return QueueBuilder.durable("deal_queue").deadLetterExchange("TOPIC_DEAD_EX").deadLetterRoutingKey("dead_fly.hahah").ttl(30000).build();
    }
    @Bean
    public Exchange dealEx(){
        return ExchangeBuilder.topicExchange("deal_ex").durable(true).build();
    }
    @Bean
    public Binding binding(Queue deal,Exchange dealEx){
        return BindingBuilder.bind(deal).to(dealEx).with("deal.fly").noargs();
    }
}
